package com.sjzxywlkj.cplife.alipay.result;

import java.util.HashMap;
import java.util.Map;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.sjzxywlkj.cplife.alipay.conn.LoginConn;
import com.sjzxywlkj.cplife.alipay.request.entity.LoginToken;
import com.sjzxywlkj.cplife.alipay.response.entity.LoginTokenResult;

/**
 * 用户授权登陆
 */

public class LoginAlipay {

    public static String login(String code) throws AlipayApiException {

        return LoginConn.login(code);
    }

    public static Map<String, String> token(String code) throws AlipayApiException {

        LoginToken loginToken = new LoginToken("authorization_code", code, null);

        Map<String, String> result = new HashMap<String, String>();
        AlipayOpenAuthTokenAppResponse response = LoginConn.token(loginToken);

        if (response.getMsg().equals("Success")) {


            int time = Integer.valueOf(response.getExpiresIn());

            if (time < 2592000) {

                loginToken.setCode(null);
                loginToken.setGrant_type("refresh_token");
                loginToken.setRefresh_token(response.getAppRefreshToken());
                response = LoginConn.token(loginToken);

            }
            LoginTokenResult loginTokenResult = new LoginTokenResult(response.getUserId(), response.getAuthAppId(), response.getAppAuthToken(), response.getAppRefreshToken(), response.getExpiresIn(), response.getReExpiresIn());
            result.put("user_id", loginTokenResult.getUser_id());
            result.put("token", loginTokenResult.getApp_auth_token());
            return result;

        } else {

            result.put("sub_msg", response.getSubMsg());
            return result;

        }


    }
}
